package com.zbvc.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zbvc.dao.AdminDao;
import com.zbvc.dao.impl.AdminDaoImpl;
import com.zbvc.entity.Admin;

/**
 * Servlet implementation class UpdateAdmin
 */
@WebServlet(name = "updateAdmin", urlPatterns = { "/updateAdmin" })
public class UpdateAdmin extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpdateAdmin() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		int tip = Integer.parseInt(request.getParameter("tip"));
		String url = request.getParameter("url");
		AdminDao adminDao = new AdminDaoImpl();
		HttpSession session = request.getSession();
		Admin admin = (Admin) session.getAttribute("admin");
		PrintWriter out = response.getWriter();
		// tip等1修改密码，否则修改个人资料
		if (tip == 1) {
			// 获取原密码和新密码
			String oldPwd = request.getParameter("password");
			String newPwd = request.getParameter("password2");
			// 如果原密码跟数据库一样，就修改，否则报"原密码不正确"
			if (admin.getPassword().equals(oldPwd)) {
				// 更新密码
				int row = adminDao.updatePassword(admin.getAid(), newPwd);
				System.out.println("更新密码" + row);
				response.sendRedirect("/bookManager/admin/" + url + ".jsp");
			} else {
				out.print("<script>alert('原密码不正确');window.history.back(-1);</script>");
			}
		} else {
			// 修改个人资料
			// 获取页面个人信息
			String name = request.getParameter("name");
			String email = request.getParameter("email");
			String phone = request.getParameter("phone");
			// 更新用户数据
			Admin a = new Admin();
			a.setAid(admin.getAid());
			a.setEmail(email);
			a.setPhone(phone);
			a.setName(name);
			int row = adminDao.updateAdminByAid(a);
			System.out.println("更新个人资料" + row + "条");
			response.sendRedirect("/bookManager/admin/" + url + ".jsp");

		}
	}

}
